/****************************************************************
 * <strong>MFDES管理类</strong>
 *
 * <p>
 * MFDES管理类
 * </p>
 *
 * @author AndyZhang 2011
 * @version 0.1
 * ToDo:
 ***************************************************************/

package com.thinkwide.data.security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

public class MFDES extends MFSecurityBase {

    private String checkPassWord(String password) {
        String defKey = "12345678";

        if (password == null || "".equals(password)) password = defKey;
        password = password + defKey;
        password = password.substring(0, 8);
        //System.out.println(password);
        return password;
    }

    public byte[] encrypt(byte[] byteContent, String password) throws Exception {
        try {

            password = checkPassWord(password);

            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            //创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            //用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            //现在，获取数据并加密
            //正式执行加密操作

            byte[] result = cipher.doFinal(byteContent);
            return result;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public byte[] decrypt(byte[] byteContent, String password) throws Exception {
        password = checkPassWord(password);
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象  
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        // 创建一个密匙工厂  
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象  
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作  
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象  
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作  
        byte[] result = cipher.doFinal(byteContent);
        return result;
    }
}
